/*
 * @Description: 全宗reducer
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-05-27 18:54:03
 */

import { delItemById, editItemById, insertItem, insertItemAfter } from '@/utils/list';
import {
  ADD_FONT,
  DELETE_FONT,
  EDIT_FONT,
  HIDE_DIALOG,
  LOADING,
  SET_FOND_LIST,
  SET_QUERY,
  SET_SELECT_FOND,
  SET_SELECT_UNIT,
  SHOW_DIALOG,
  SHOW_EDIT_DIALOG
} from '../constants';

export const FondsReducer = (state, action) => {
  switch (action.type) {
    // 表格加载loading
    case LOADING:
      return { ...state, loading: true };

    /**
     * @description: 加载表格数据及相关数据
     * @param {Array} data.results 表格数据
     * @param {Number} TotalCount 数据总数量
     * @return {*}
     */
    case SET_FOND_LIST: {
      return {
        ...state,
        list: action.data,
        selectFondId: action.data.length > 0 ? action.data[0].id : 0,
        loading: false
      };
    }

    /**
     * @description: 设置选中的单位
     * @param {Obj} data 选中的单位Object
     */
    case SET_SELECT_UNIT: {
      return {
        ...state,
        selectUnit: action.data
      };
    }

    /**
     * @description: 设置选中的单位
     * @param {number} index 选中的全宗ID
     */
    case SET_SELECT_FOND: {
      return {
        ...state,
        selectFondId: action.id
      };
    }

    // 加载表格数据及相关数据
    case SET_QUERY: {
      const listQuery = { ...state.listQuery };
      action.info.forEach(({ key, value }) => {
        listQuery[key] = value;
      });

      return {
        ...state,
        listQuery
      };
    }

    /**
     * @description: 添加全宗
     * @param {Object} data 新增的全宗
     */
    case ADD_FONT:
      return {
        ...state,
        list: insertItemAfter(action.data, state.list),
        selectFondId: action.data.id,
        dialog: { visible: false }
      };

    /**
     * @description: 编辑全宗
     * @param {Object} data 编辑的全宗
     */
    case EDIT_FONT: {
      break;
    }

    /**
     * @description: 删除全宗
     * @param {Number} id 删除全宗的ID
     */
    case DELETE_FONT: {
      const list = delItemById(action.id, state.list);
      const selectFondId = list.length > 0 ? list[0].id : 0;
      return { ...state, list, selectFondId };
    }

    default:
      console.log('untouched', action);
      return state;
  }
};
